package com.gusha.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.gusha.config.SysOperateLog;
import com.gusha.dao.SysLogOperateDao;
import com.gusha.model.SysAdmin;
import com.gusha.model.SysLogOperate;
import com.gusha.utils.DateUtils;
import com.gusha.utils.IpUtils;

@Component
public class LoginAdminInterceptor implements HandlerInterceptor{
	
	@Autowired
	private SysLogOperateDao sysLogOperateDao;
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception {
		try {
			HandlerMethod handler2 = (HandlerMethod) handler;
			SysOperateLog sysOperateLog = handler2.getMethod().getAnnotation(SysOperateLog.class);
			if (null != sysOperateLog) {
				SysLogOperate log = new SysLogOperate();
				SysAdmin sysAdmin = (SysAdmin) request.getSession().getAttribute("admin");
				log.setSysAdmin(sysAdmin);
				log.setCreateTime(DateUtils.getNow());
				log.setIp(IpUtils.getIpAddr(request));
				log.setTitle(sysOperateLog.operate());
				log.setComplete("执行成功！");
				// 如果controller报错，则记录异常错误
				if (e != null) {
					log.setComplete("执行失败");
					sysLogOperateDao.saveAndFlush(log);
				}
				try {
					log.setComplete("执行成功！");
					sysLogOperateDao.saveAndFlush(log);
				} catch (Exception e1) {
					log.setComplete("执行失败");
					sysLogOperateDao.saveAndFlush(log);
				}
			}
		} catch (Exception el) {
			el.printStackTrace();
		}
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求的URL  
        //String url = request.getRequestURI();
        //识别ajax的响应头
        String requestType = request.getHeader("X-Requested-With");
        //获取Session  
        HttpSession session = request.getSession(); 
        if(session.getAttribute("admin") != null){  
            return true;  
        }  
        if (requestType != null && requestType.equals("XMLHttpRequest")) {//如果是ajax类型，响应logout给前台  
            response.getWriter().print("nologin");  
        }else{  
            response.sendRedirect(request.getContextPath()+"/");//首页居多  
        }  
        return false;
	}

}
